﻿using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using Contract;
using Microsoft.Practices.Unity.InterceptionExtension;

namespace WcfInfrastructure
{
    /// <summary>
    /// Replaces the default IInstanceProvider class used by WCF.  This is needed so Unity's interception libraries can be used to
    /// intercept method calls.  Unity is configured to intercept all method calls to the IMath interface and uses the CustomBehavior
    /// class to handle those calls.
    /// </summary>
    /// <remarks>http://msdn.microsoft.com/en-us/library/ms599837(v=vs.100)</remarks>
    public class MathInstanceProvider : IInstanceProvider
    {
        /// <summary>
        /// http://msdn.microsoft.com/en-us/library/ms587087(v=vs.100).aspx
        /// </summary>
        /// <param name="instanceContext"></param>
        /// <returns></returns>
        public object GetInstance(InstanceContext instanceContext)
        {
            return null;
        }

        /// <summary>
        /// http://msdn.microsoft.com/en-us/library/ms587089(v=vs.100).aspx
        /// </summary>
        /// <param name="instanceContext"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public object GetInstance(InstanceContext instanceContext, Message message)
        {
            var instance = Intercept.ThroughProxy<IMath>(
                new Implementation.Math(), 
                new InterfaceInterceptor(),
                new[] {new CustomBehavior()});

            return instance;
        }

        /// <summary>
        /// http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.iinstanceprovider.releaseinstance(v=vs.100).aspx
        /// </summary>
        /// <param name="instanceContext"></param>
        /// <param name="instance"></param>
        public void ReleaseInstance(InstanceContext instanceContext, object instance)
        {
            //create a new instance each time, no need to release
        }
    }
}
